import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);
const originalPush = VueRouter.prototype.push;
//修改对象的原型中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};
import Home from "../views/Home.vue";
const routes = [
  {
    path: "/",
    name: "home",
    component: Home,
  },
  {
    path: "/product",
    name: "product",
    component: () =>
      import(/* webpackChunName："product" */ "../views/Product.vue"),
  },
  {
    path: "/detail/:id",
    name: "detail",
    component: () =>
      import(/* webpackChunName："product" */ "../views/Detail.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunName："product" */ "../views/Login.vue"),
  },
  {
    path: "/order",
    name: "order",
    component: () =>
      import(/* webpackChunName："product" */ "../views/Order.vue"),
    children: [
      {
        path: "orderconfirm",
        name: "orderconfirm",
        component: () =>
          import(/* webpackChunName："product" */ "../views/OrderConfirm.vue"),
      },
      {
        path: "orderlist",
        name: "orderlist",
        component: () =>
          import(/* webpackChunName："product" */ "../views/OrderList.vue"),
      },
      {
        path: "orderpay",
        name: "orderpay",
        component: () =>
          import(/* webpackChunName："product" */ "../views/OrderPay.vue"),
      },
    ],
  },
  {
    path: "/cart",
    name: "cart",
    component: () =>
      import(/* webpackChunName："product" */ "../views/Cart.vue"),
  },
  {
    path: "/register",
    name: "register",
    component: () =>
      import(/* webpackChunName："product" */ "../views/Register.vue"),
  },
  {
    path: "/address",
    name: "address",
    component: () =>
      import(/* webpackChunName："product" */ "../views/Address.vue"),
  },
  {
    path: "/person",
    name: "person",
    component: () =>
      import(/* webpackChunName："product" */ "../views/Person.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
router.beforeEach((to, from, next) => {
  let token = sessionStorage.getItem("token");
  if (token || ["login", "home", "product", "detail"].includes(to.name)) {
    next();
  } else {
    alert("请登录");
    next("/login");
  }
});
export default router;
